package com.cslc.wechat.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.cslc.wechat.common.dto.AccessTokenInfo;

public class QRUtil {

	private static Logger logger=Logger.getLogger(QRUtil.class);
	/**
	 * 创建永久二维码    获取二维码的ticket
	 */
	public static String  createPermanentQRCode(String sceneId,String savePath){
		String ticket=null;
		String filePath=null;
		String url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
		AccessTokenInfo accessToken = WeChatUtil.getAccessToken();
		String requestUrl=url.replace("TOKEN", accessToken.getToken());
		String jsonMsg="{\"action_name\": \"QR_LIMIT_STR_SCENE\",\"action_info\": {\"scene\": {\"scene_str\": \"sceneId\"}}}";
		JSONObject jsonObject=WeChatUtil.httpRequest(requestUrl, "POST", jsonMsg.replace("sceneId", sceneId));
		
		if(jsonObject!=null){
			try {
				ticket=jsonObject.getString("ticket");
				logger.info("获取二维码ticket成功！"+ticket);
			} catch (Exception e) {
				int errorCode=jsonObject.getInt("errcode");
				String errorMsg=jsonObject.getString("errmsg");
				logger.debug("获取二维码ticket失败！"+"错误代码："+errorCode+",错误信息"+errorMsg);
			}
		}
		/**
		 * 成功获取ticket之后换取二维码
		 */
		String getQRRequestUrl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
		
		getQRRequestUrl=getQRRequestUrl.replace("TICKET", ticket);
		
		try {
			URL qrurl=new URL(getQRRequestUrl);
			HttpsURLConnection connection=(HttpsURLConnection) qrurl.openConnection();
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			if (!savePath.endsWith("/")) {
				savePath+="/";
			}
			
			//用ticket作为文件名   避免重复文件名覆盖
			filePath=savePath+ticket+".jpg";
			
			BufferedInputStream bis=new BufferedInputStream(connection.getInputStream());
			FileOutputStream fos =new FileOutputStream(new File(filePath));
			byte[] bytes=new byte[8096];
			int size=0;
			while((size=bis.read(bytes))!=-1){
				fos.write(bytes, 0, size);
			}
			fos.close();
			bis.close();
			
			connection.disconnect();
			
		} catch (Exception e) {
			logger.debug("创建二维码失败！"+e);
			filePath=null;
		}
		return filePath;
	}
}
